#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
#=============================================================================
#     FileName: dbhelper.py
#         Desc: dbhelper for pynhk
#      License: GPL
#       Author: Steve Lemuel
#        Email: wlemuel@hotmail.com
#      Version: 0.0.1
#   LastChange: 2015-09-07 15:21:54
#    CreatedAt: 2015-09-07 15:21:54
#=============================================================================
"""
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from config import DB_NAME
from model import Base, News

engine = create_engine('sqlite:///' + DB_NAME, echo=False)
Base.metadata.create_all(engine)
DBSession = sessionmaker(bind=engine)


class DBHelper:
    def __init__(self):
        self.db = DBSession()

    def insert(self, obj):
        self.db.add(obj)
        self.commit()

    def inserts(self, objs):
        if type(objs) != list: return
        for i in objs:
            #i and self.db.add(i) or i
            self.insert(i)
        self.commit()

    def select(self, clazz, limit=None, **kwargs):
        results = []
        try:

            if limit:
                results = self.db.query(clazz).filter_by(**kwargs).limit(limit).all()
            else:
                results = self.db.query(clazz).filter_by(**kwargs).all()
        except Exception, e:
            pass

        return results

    def commit(self):
        try:
            self.db.commit()
        except Exception, e:
            self.db.rollback()

    def update(self, clazz, content, **kwargs):
        obj = self.db.query(clazz).filter_by(**kwargs).update(content)
        self.commit()

    def exists(self, clazz, **kwargs):
        try:
            count = self.db.query(clazz).filter_by(**kwargs).count()
            return count > 0
        except Exception:
            return False

    def __del__(self):
        self.db.close()


if __name__ == '__main__':
    # import sys
    # reload(sys)
    # sys.setdefaultencoding('utf-8')

    db = DBHelper()
    import pdb
    pdb.set_trace()
    # print db.select(News)
    print map(lambda x: x, db.select(News))
